<template>
  <el-radio-group v-model="modelValue" @change="handleChange">
    <el-radio-button key="" value="" v-if="showAll">全部</el-radio-button>
    <el-radio-button
      v-for="item in options"
      :key="item.key"
      :value="item.key"
    >{{item.value}}</el-radio-button>
  </el-radio-group>
</template>

<script setup>
import { ref, watch } from 'vue';

const modelValue = defineModel();
const emit = defineEmits(['change']);
const props = defineProps({
  options: [Array, String],
  showAll: {
    type: Boolean,
    default: false
  },
});
const options = ref([]);

const init = (data) => {
  if (data) {
    if (Array.isArray(data)) {
      options.value = data;
    } else if (typeof data === 'string') {
      const optionList = [];
      data.split(',').forEach(item => {
        optionList.push({key: item, value: item});
      });
      options.value = optionList;
    }
  }
};

const handleChange = () => {
  emit('change', modelValue.value);
};

watch(() => props.options, (data) => {
  init(data);
}, {immediate: true});
</script>